import * as express from 'express'
import { prisma } from '../generated/prisma-client';
import { getUserId } from '../util';
import * as multer from 'multer'
import * as path from 'path';
import * as fs from 'fs'
import { request } from 'http';

const upload = multer({ dest: path.join(__dirname, '../build/app/') });

const router = express.Router()

router.get(`/list`, async (req, res) => {

    const result = await prisma.newses({
        orderBy: "createdAt_DESC"
    }).$fragment(`
    fragment News on news {
        id
        title
        content
        imgSrc
        cuser {
            id
            name
        }
        createdAt
    }
`)

    return res.json(result)

})

router.post('/add', upload.array('files'), async (req, res) => {

    const { title, content } = req.body

    const userMsgs = await getUserId(req.headers['authorization'])


    if (req.files instanceof Array) {

        if (req.files.length === 0) {
            await prisma.createCases({
                title: title,
                image: "",
                cuser: {
                    connect: {
                        id: userMsgs.adminUserId
                    }
                },
            })
        }
        for (let i = 0; i < req.files.length; i++) {

            const Time = new Date().getTime()

            const ext = req.files[i].originalname.split('.')[1];

            const temp_path = req.files[i].path;

            const target_path = req.files[i].destination + `news${Time}_${i}.${ext}`

            console.log(target_path)

            fs.rename(temp_path, target_path, async (error: any) => {
                if (!error) {
                    console.log('上传成功')
                    await prisma.createNews({
                        imgSrc: `news${Time}_${i}.${ext}`,
                        title: title,
                        content: content,
                        cuser: {
                            connect: {
                                id: userMsgs.adminUserId
                            }
                        }
                    })
                }
            });
        }
    }
    return res.json({
        success: true
    })

})


router.post('/edit', upload.single('files') ,async (req, res) => {

    const { id, title, content ,imgSrc} = req.body

    const Id = parseInt(id ,10)

    if (req.file) {

        const temp_path = req.file.path;

        const target_path = req.file.destination + imgSrc

        fs.rename(temp_path, target_path, async (error: any) => {
            if (!error) {
            }
        });
    }

    const result = await prisma.updateNews({
        where: {
            id: Id
        },
        data: {
            title: title,
            content: content
        }
    })

    return res.json(result)

})


router.post('/delete', async (req, res) => {

    const { ids } = req.body

    const idsNum = ids.map(Number)

    const deletedPics = await prisma.newses({ where: { id_in: ids } })

    for (let i = 0; i < deletedPics.length; i++) {
        if(deletedPics[i].imgSrc){
            await fs.unlinkSync(path.join(__dirname, '../build/app/') + `${deletedPics[i].imgSrc}`)
        }
    }

    const result = await prisma.deleteManyNewses({
        id_in: idsNum
    })

    return res.json(result)

})

router.post('/new',async (req, res) => {
    const {id} = req.body
    const result = await prisma.news({
        id:parseInt(id,10)
    })
    return res.json(result)
})

module.exports = router